﻿/// <reference path=jquery-1.3.2-vsdoc2.js>
(function($) {

    /*
    Validation Singleton
    */
    var Validation = function() {

        var rules = {

            email: {
                check: function(value) {

                    if (value)
                        return testPattern(value, "[a-zA-Z0-9_.]{2,}@[a-zA-Z0-9_]{2,}\.[a-zA-Z_]{2,}");
                    return true;
                },
                msg: "Invalid email format. <a href='http://en.wikipedia.org/wiki/E-mail_address' target='_blank' title=''>Email format</a>."
            },
            numeric: {
                check: function(value) {

                    if (value)
                        return testPattern(value, "\\w*[\+-]?\\w?\\d+(\\d*\\.?\\d{3}?){0,}");
                    return true;
                },
                msg: "Invalid number."
            },
            url: {

                check: function(value) {

                    if (value)
                        return testPattern(value, "https?://(.+\.)+.{2,4}(/.*)?");
                    return true;
                },
                msg: "Định dạng url không đúng. <a href='http://www.w3schools.com/HTML/html_url.asp' target='_blank' title=''>Định nghĩa URL</a>"
            },
            required: {

                check: function(value) {

                    if (value)
                        return true;
                    else
                        return false;
                },
                msg: "Thông tin bắt buộc phải nhập."
            },
            minlen: {
                check: function(value) { return true; },
                msg: "Thông nhập phải có độ dài ít nhất là..."
            },
            maxlen: {
                check: function(value) { return true; },
                msg: "Thông nhập phải có độ dài lớn nhất nhỏ hơn..."
            }
        };
        var testPattern = function(value, pattern) {

            var regExp = new RegExp("^" + pattern + "$", "");
            return regExp.test(value);
        };
        return {

            addRule: function(name, rule) {
                if (rules[name] == undefined)
                    rules[name] = rule;
            },
            getRule: function(name) {

                return rules[name];
            }
        };
    };

    /* 
    Form factory 
    */
    var Form = function(form) {

        var fields = [];
        form.find("input[validation], textarea[validation]").each(function() {
            fields.push(new Field(this));
        });
        this.fields = fields;
    };
    Form.prototype = {
        validate: function() {

            for (field in this.fields) {

                this.fields[field].validate();
            }
        },
        isValid: function() {

            for (field in this.fields) {

                if (!this.fields[field].valid) {

                    this.fields[field].field.focus();
                    return false;
                }
            }
            return true;
        }
    };

    /* 
    Field factory 
    */
    var Field = function(field) {

        this.field = $(field);
        this.valid = false;
        this.attach("change");

        var types = $(field).attr('validation').split(' ');
        if (typeof (types) != 'undefined') {
            for (var i = 0; i < types.length; i++) {
                if (types[i] == 'required') $(field).addClass('required');
                if (types[i] == 'numeric') {
                    $(field).addClass('red alignRight');
                    this.attach("keypress");
                    this.attach("keyup");
                }
            }
        }
        /*
        Create tooltip    
        */
        var tooltip = document.createElement("div");
        tooltip.className = "DIVTooltip";
        var tooltipcontainer = document.createElement("div");
        tooltipcontainer.className = "DIVTooltipContainer red"
        tooltip.appendChild(tooltipcontainer);

        //document.getElementsByTagName("body")[0].appendChild(tooltip);
        $('#main').append(tooltip);

        var position = $(field).position();
        $(tooltip).css({
            'top': position.top,
            'left': Math.floor(position.left) + Math.floor($(field).width()) + 15
        });

        this.tooltip = $(tooltip);
    };
    Field.prototype = {

        attach: function(event) {

            var obj = this;
            if (event == "change") {
                obj.field.bind("change", function() {
                    return obj.validate();
                });
            }
            if (event == "keyup") {
                obj.field.bind("keyup", function(e) {
                    obj.field.val(formatCurrencyWithoutDecimalAndDolar(obj.field.val()));
                    return obj.validate();
                });
            }
            if (event == "keypress") {
                obj.field.bind("keypress", function(e) {
                    if (e.keyCode && e.keyCode != 8) {
                        if ((e.keyCode <= 57 && e.keyCode >= 48) || e.keyCode == 0 || e.keyCode == 36) {
                            return true;
                        }
                        else {
                            return false;
                        }
                    }
                    else {
                        if ((e.charCode <= 57 && e.charCode >= 48) || e.charCode == 0 || e.charCode == 36) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
            }
        },
        validate: function() {

            var obj = this,
                    field = obj.field,
                    tooltip = obj.tooltip,
                    errorClass = 'errorlist',
                    errorlist = $(document.createElement("ul")).addClass(errorClass),
                    types = field.attr("validation").split(" "),
                    errors = [];

            tooltip.hide();
            tooltip.find('.' + errorClass).remove();

            for (var i = 0; i < types.length; i++) {

                var rule = $.Validation.getRule(types[i]);
                if (rule && !rule.check(field.val())) {

                    errors.push(rule.msg);
                }
            }
            if (errors.length > 0) {

                obj.field.unbind("keyup")
                obj.attach("keyup");
                for (error in errors) {

                    errorlist.append("<li>" + errors[error] + "</li>");
                }
                obj.valid = false;

                errorlist.appendTo(tooltip.find('.DIVTooltipContainer'));
                tooltip.show();
            }
            else {
                errorlist.remove();
                tooltip.hide();
                obj.valid = true;
            }
        }
    };

    /* 
    Validation extends jQuery prototype
    */
    $.extend($.fn, {

        validation: function() {

            var validator = new Form($(this));
            $.data($(this)[0], 'validator', validator);

            $(this).bind("submit", function(e) {
                validator.validate();
                if (!validator.isValid()) {
                    e.preventDefault();
                }

                for (i = 0; i < parent.frames.length; ++i)
                    if (parent.frames[i].FCK)
                    parent.frames[i].FCK.UpdateLinkedField();

            });
        },
        validate: function() {

            var validator = $.data($(this)[0], 'validator');
            validator.validate();
            return validator.isValid();

        }
    });
    $.Validation = new Validation();
})(jQuery);